package com.jiang.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    private static String URL;
    private static String DRIVER;
    private static String USERNAME;
    private static String PASSWORD;
    private static Connection conn;
    private static PreparedStatement ps=null;
    private static ResultSet rs=null;
//    static{
//        try {
//            Properties yaml = new Properties ( );
//            InputStream is = JdbcUtil.class.getClassLoader ( ).getResourceAsStream ("mysql.yaml");
//            yaml.load (is);
//            URL=yaml.getProperty ("url");
//            DRIVER=yaml.getProperty ("driver");
//            USERNAME=yaml.getProperty ("username");
//            PASSWORD=yaml.getProperty ("password");
//            Class.forName (DRIVER);
//           conn = DriverManager.getConnection (URL, USERNAME, PASSWORD);
//        }catch(Exception e){
//            e.printStackTrace ();
//        }
//    }
    public static Connection getConn(){
        try {
            Properties yaml = new Properties ( );
            InputStream is = JdbcUtil.class.getClassLoader ( ).getResourceAsStream ("mysql.yaml");
            yaml.load (is);
            URL=yaml.getProperty ("url");
            DRIVER=yaml.getProperty ("driver");
            USERNAME=yaml.getProperty ("username");
            PASSWORD=yaml.getProperty ("password");
            Class.forName (DRIVER);
           conn = DriverManager.getConnection (URL, USERNAME, PASSWORD);
        }catch(Exception e){
            e.printStackTrace ();
        }
        return conn;
    }
    public static PreparedStatement getPs(String sql){
        try {
            ps = conn.prepareStatement (sql);
        } catch (SQLException e) {
            e.printStackTrace ( );
        }
        return ps;
    }
    public static ResultSet getRs(){
        try {
            rs=ps.executeQuery ();
        } catch (SQLException e) {
            e.printStackTrace ( );
        }
        return rs;
    }
    public static void closeAll(){
       if (rs!=null){
           try {
               rs.close ();
           } catch (SQLException e) {
               e.printStackTrace ( );
           }
       }
       if (ps!=null){
           try {
               ps.close ();
           } catch (SQLException e) {
               e.printStackTrace ( );
           }
       }
       if (conn!=null){
           try {
               conn.close ();
           } catch (SQLException e) {
               e.printStackTrace ( );
           }
       }
    }
}
